<?php
/**
 * @author spenceryg
 * @date 2023/4/9
 * @time 12:03 上午
 * @focus love & life
 */


namespace app\api1\controller;

use app\auto\model\Method;
use app\common\model\Orders;
use GuzzleHttp\Client;
use hg\apidoc\annotation as Apidoc;

use app\BaseController;
use app\common\model\MemberPointsLog;
use app\common\model\Order;
use app\common\model\PointProducts;
use hg\apidoc\utils\Cache;
use Yansongda\Pay\Exception\ContainerException;
use Yansongda\Pay\Pay;
use EasyWeChat\Factory;

/**
 * Class PointPay
 * @package app\api\controller
 * @Apidoc\Title("支付管理")
 * @Apidoc\Group("api")
 */
class RobotPay extends BaseController
{

    /**
     * checkTerrace
     * @return mixed
     */
    public function pay()
    {
        $pay_type = $this->getPayType(); //该方法使用来判断用户扫码终端的
        $data = input();
        if ($pay_type === 'alipay') { //如果用户是通过支付宝扫码，进行支付宝相关操作
            $this->aliPay($data);
        } elseif ($pay_type === 'wechat') { //如果用户是通过微信扫码，进行微信相关操作
            $this->wePay($data);
        } elseif ($pay_type === false) {
            $this->wePay($data);
            echo "请使用支付宝或微信进行扫码";
            exit;
        }
    }

    /**
     * 判断扫码终端
     *
     * @return string|boolean
     */
    private function getPayType()
    {
        if (strstr($_SERVER['HTTP_USER_AGENT'], 'AlipayClient')) {
            return "alipay";
        } elseif (strstr($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger')) {
            return "wechat";
        } else {
            return false;
        }
    }


    private function aliPay($param)
    {
        try {
            $newOrder = \app\common\model\NewOrders::find($param['id']);
            $subject = $newOrder['name'];
            return Pay::alipay(config('alipay_payment'))->wap([
                'out_trade_no' => 'robot_' . $newOrder->id,
                'total_amount' => $newOrder['total_amount'],
                'subject' => $subject,
            ])->send();
        } catch (\Exception $e) {
            dump($e);
            exit;
        }

    }



    private function wePay($param)
    {

        $config = [
            'app_id' => config('front_end.app_id'),
            'secret' => config('front_end.secret'),
            'response_type' => 'array',
        ];

        $app = Factory::miniProgram($config);
        $access_token = $app->access_token->getToken()['access_token'];
        $client = new Client();
        $res = $client->post("https://api.weixin.qq.com/wxa/generatescheme?access_token=" . $access_token, [
            'json' => [
                'jump_wxa' => [
                    'query' => 'id=' . $param['id'] . '&uid=' .  $param['member_id'],
                    'path' => 'pages/wepay/wepayRobot'
                ]
            ]
        ]);


        $res = $res->getBody()->getContents();
        // 重定向, 使用header跳转
        $res = json_decode($res, true);  // 转数组  方便取值
        $url = $res['openlink'];
        header("Location:" . $url);
        exit;

    }




}
